<template>
  <div class="SMS-template">
    <div class="search">
      <ul>
        <li>
          <span>模板名</span>
          <el-input
            placeholder="请输入模板名"
            v-model.trim="templateName"
            @keyup.enter.native="searchTemplate"
            @input="aearchInput"
            clearable
          ></el-input>
        </li>
        <li>
          <span>使用状态</span>
          <el-select v-model="templateStatus" placeholder="全部" @change="searchTemplate">
            <el-option
              v-for="item in statusOptions"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            ></el-option>
          </el-select>
        </li>
        <li>
          <el-button type="primary" @click="searchTemplate" icon="el-icon-search">查询</el-button>
        </li>
      </ul>
    </div>
    <div class="modify">
      <el-button type="primary" icon="el-icon-plus" @click="addTemplate">添加</el-button>
      <el-button
        type="primary"
        icon="el-icon-minus"
        @click="deleteTemplate"
        :disabled="isDisable"
      >删除</el-button>
    </div>
    <el-card>
      <el-table
        :data="tableData"
        style="width: 100%"
        @row-click="rowClickHandle"
        @selection-change="selectChange"
        ref="table"
        v-loading="loading"
        element-loading-text="加载中"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="id" label="模板ID" width="80"></el-table-column>
        <el-table-column prop="name" label="模板名称" width="200"></el-table-column>
        <el-table-column label="使用状态" width="150">
          <template v-slot="scope">
            <el-tag type="success" v-if="scope.row.status===1">使用中</el-tag>
            <el-tag type="danger" v-else>未使用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contents" label="模板内容"></el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template v-slot="scope">
            <el-button
              type="primary"
              @click="editTemplate(scope.$index)"
              size="small"
              icon="el-icon-edit"
            >修改</el-button>
            <el-button
              type="danger"
              @click="deleteSMS(scope.row)"
              size="small"
              icon="el-icon-delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="changePage"
        :current-page="pageNum"
        :page-sizes="[10,20,30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 新增模板 -->
    <el-dialog title="添加模板" :visible.sync="addDialogVisible" width="30%" center>
      <el-form ref="templateFome" :model="addTemplateForm" label-width="80px">
        <el-form-item label="模板名称">
          <el-input v-model="addTemplateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="使用状态">
          <el-select v-model="addTemplateForm.status" placeholder="请选择">
            <el-option
              v-for="item in useStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容">
          <el-input
            type="textarea"
            v-model="addTemplateForm.contents"
            :autosize="{ minRows: 4, maxRows: 4}"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改模板对话框 -->
    <el-dialog title="修改模板" :visible.sync="editDialogVisible" width="30%" center>
      <el-form ref="editFoem" :model="editForm" label-width="80px">
        <el-form-item label="模板名称">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="使用状态">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option
              v-for="item in useStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容">
          <el-input
            type="textarea"
            v-model="editForm.contents"
            :autosize="{ minRows: 4, maxRows: 4}"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from "../utils/qs";
export default {
  data() {
    return {
      loading: false,
      // 状态选项
      statusOptions: [
        {
          status: 0,
          label: "全部",
        },
        {
          status: 1,
          label: "使用中",
        },
        {
          status: 2,
          label: "未使用",
        },
      ],
      // 使用状态
      useStatus: [
        { value: 1, label: "使用中" },
        { value: 2, label: "未使用" },
      ],
      // 添加模板对象表单
      addTemplateForm: {},
      // 新增模板对话框
      addDialogVisible: false,
      // 修改模板
      editDialogVisible: false,
      // 修改模板对象表单
      editForm: {},
      // 搜索模板
      templateName: "",
      // 搜索状态
      templateStatus: "",
      // 当前页
      pageNum: 1,
      // 当前页数据条数
      pageSize: 10,
      // 总页数
      totalPage: 1,
      // 数据总条目数
      total: 1,
      // 列表数据
      tableData: [],
      // 选中的模板
      checkedTemplat: [],
    };
  },
  methods: {
    // 显示数量切换
    handleSizeChange(num) {
      this.pageSize = num;
      this.requestData();
    },
    // 请求数据{
    requestData(page = this.pageNum, size = this.pageSize) {
      this.loading = true;
      this.$http("/trademark/template/findByPage", {
        params: { pageNum: page, pageSize: size },
      })
        .then(
          ({ data: response }) => {
            if (response.code !== 200)
              return this.$message.error("数据请求失败");
            this.tableData = response.data.list;
            this.pageNum = response.data.pageNum;
            this.pageSize = response.data.pageSize;
            this.total = response.data.total;
            this.totalPage = response.data.totalPage;
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    // 修改模块请求
    requestEdit() {
      var formData = new FormData();
      for (let key in this.editForm) {
        formData.append(key, this.editForm[key]);
      }
      return this.$http.put("/trademark/template/update", formData);
    },
    // 添加模块请求
    requestAdd() {
      return this.$http("/trademark/template/add", {
        params: {
          contents: this.addTemplateForm.contents,
          id: this.addTemplateForm.id,
          name: this.addTemplateForm.name,
          status: this.addTemplateForm.status,
        },
      });
    },

    // 取消搜索
    cancleSearch() {
      this.templateName = "";
      this.templateStatus = "";
      this.requestData();
    },
    // 模板查询请求
    requestSearch(key, val) {
      this.loading = true;
      if (val === 0) return this.requestData();
      this.$http(`/trademark/template/findByType?${key}=${val}`)
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("查询失败");
            this.tableData = response.data;
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    //搜索模板
    searchTemplate() {
      if (this.templateName) {
        this.requestSearch("name", this.templateName);
      } else if (this.templateStatus || this.templateStatus === 0) {
        this.requestSearch("status", this.templateStatus);
      } else {
        this.$message({
          duration: 2000,
          showClose: true,
          type: "warning",
          message: "内容不能为空",
        });
      }
    },
    // 删除模板
    async deleteSMS(row) {
      const confirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirm !== "confirm") return this.$message.info("已取消删除");
      this.loading = true;
      this.$http
        .delete("/trademark/template/delete?id=" + row.id)
        .then(({ data: response }) => {
          if (response.code !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.requestData();
        })
        .catch((err) => err)
        .finally(() => (this.loading = false));
    },

    // 批量删除模板
    requestDelates(arr) {
      this.loading = true;
      this.$http
        .delete("/trademark/template/batch" + qs(arr, "ids"))
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("删除失败");
            this.requestData();
            this.$message.success("删除成功");
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    // 添加模板
    addTemplate() {
      this.addDialogVisible = true;
    },
    // 修改模板
    editTemplate(index) {
      this.editForm = { ...this.tableData.slice(index, index + 1)[0] };
      this.editDialogVisible = true;
    },
    // 确认修改
    editConfirm() {
      this.loading = true;
      this.requestEdit()
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("修改失败");
            this.requestData();
            this.$message.success("修改成功");
          },
          (err) => (this.loading = false)
        )
        .finally(() => (this.loading = false));
      this.editDialogVisible = false;
    },
    // 确认添加
    addConfirm() {
      this.loading = true;
      this.requestAdd()
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("添加失败");
            this.requestData();
            this.$message.success("添加成功");
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
      this.addDialogVisible = false;
    },
    changePage(page) {
      this.pageNum = page;
      this.requestData();
    },
    // 选中行
    rowClickHandle(row, column, event) {
      const target = event.target;
      if (
        target.nodeName === "BUTTON" ||
        target.parentElement.nodeName === "BUTTON"
      )
        return;
      this.$refs.table.toggleRowSelection(
        this.tableData.filter((val) => val.id === row.id)[0]
      );
    },
    // 选中事件
    selectChange(selection) {
      this.checkedTemplat = selection;
    },
    // 删除选中
    deleteTemplate() {
      var ids = this.checkedTemplat.map((val) => val.id);
      this.requestDelates(ids);
    },
    // 查询内容改变
    aearchInput() {
      this.onSearch || this.requestData();
    },
  },
  computed: {
    // 是否处于搜索状态
    onSearch() {
      return !!this.templateName || !!this.templateStatus;
    },
    // 删除按钮禁用状态
    isDisable() {
      return !this.checkedTemplat.length;
    },
  },
  created() {
    this.requestData();
  },
};
</script>
<style lang="less" scoped>
.SMS-template {
  .search {
    padding: 10px 0;
    ul {
      overflow: hidden;
      li {
        float: left;
        display: flex;
        flex-direction: row;
        span {
          white-space: nowrap;
          line-height: 40px;
          font-size: 16px;
          font-weight: 600;
          margin-right: 10px;
        }
      }
      li + li {
        margin-left: 20px;
      }
    }
  }
  .modify {
    padding: 10px 0;
  }
  .el-pagination {
    float: left;
    margin: 20px 50%;
    margin: 20px 0;
  }
}
</style>